package com.zzy.util.file;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class UtilFileUpload {


    /**
     *
     * @param file  例：File file = new File("F:/shayatou.jpg");
     * @param savePath 例：	/resources/upload/touxiang/shayatou.jpg
     * @param response
     * @param request
     */
    public static void uploadCommon(File file, String savePath, HttpServletResponse response, HttpServletRequest request){
        byte[] buffer=new byte[10240];
        //读取文件
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //保存文件并设置保存目录路径
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(savePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if(!file.exists()) {
            file.mkdirs();
        }else{
            //String filesize = file.length()/1024+"KB";
            int length = 0;
            try {
                length = fis.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            while(length>0){
                //每次写入length长度内容
                try {
                    fos.write(buffer,0, length);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                fis.close();
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //上传文件的保存路径
    protected String configPath = "upload/widget";
    protected String dirTemp = "upload/widget/temp";
    protected String dirName = "file";
    /**单文件上传
     * @param f (要上传的文件)
     * @param src (要上传文件地址)
     */
    public  void uploadFile(File f,String src,HttpServletRequest req, HttpServletResponse res){
        try {
            req.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        res.setContentType("txt/html; charset=UTF-8");
        PrintWriter out = null;
        try {
            out = res.getWriter();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        //文件保存目录路径
        String savePath = "E:/";
        //String savePath = this.getServletContext().getRealPath("/") + configPath;
        // 临时文件目录
        String tempPath = "";//this.getServletContext().getRealPath("/") + dirTemp;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String ymd = sdf.format(new Date());
        savePath += "/" + ymd + "/";
        //创建文件夹
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        tempPath += "/" + ymd + "/";
        //创建临时文件夹
        File dirTempFile = new File(tempPath);
        if (!dirTempFile.exists()) {
            dirTempFile.mkdirs();
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(20 * 1024 * 1024); //设定使用内存超过5M时，将产生临时文件并存储于临时目录中。
        factory.setRepository(new File(tempPath)); //设定存储临时文件的目录。
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        try {
            List items = upload.parseRequest(req);
            System.out.println("items = " + items);
            Iterator itr = items.iterator();

            while (itr.hasNext())
            {
                FileItem item = (FileItem) itr.next();
                String fileName = item.getName();
                @SuppressWarnings("unused")
                long fileSize = item.getSize();
                if (!item.isFormField()) {
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                    String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                    try{
                        File uploadedFile = new File(savePath, newFileName);

                        OutputStream os = new FileOutputStream(uploadedFile);
                        InputStream is = item.getInputStream();
                        byte buf[] = new byte[1024];//可以修改 1024 以提高读取速度
                        int length = 0;
                        while( (length = is.read(buf)) > 0 ){
                            os.write(buf, 0, length);
                        }
                        //关闭流
                        os.flush();
                        os.close();
                        is.close();
                        System.out.println("上传成功！路径："+savePath+"/"+newFileName);
                        out.print(savePath+"/"+newFileName);
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }else {
                    String filedName = item.getFieldName();
                    System.out.println("===============");
                    try {
                        System.out.println(new String(item.getString().getBytes("iso-8859-1"),"utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    System.out.println("FieldName："+filedName);
                    // 获得裁剪部分的坐标和宽高
                    System.out.println("String："+item.getString());
                }
            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        out.flush();
        out.close();
    }







    /*
中文单位		中文简称		英文单位		英文简称	进率（Byte=1）
位			比特			bit				b	0.125
字节			字节			Byte			B	1
千字节		千字节		Kilo Byte		KB	2^10
兆字节		 兆			Mega Byte		MB	2^20
吉字节		吉			Giga Byte   	GB	2^30
太字节		太 			Trillion Byte	TB	2^40
拍字节 		拍 			Peta Byte		PB  2^50
艾字节             	艾			Exa Byte		EB	2^60
泽它字节		泽			Zetta Byte		ZB	2^70
尧它字节		尧			Yotta Byte		YB	2^80
千亿亿亿字节	千亿亿亿字节	Bront Byte		BB	2^90
百万亿亿亿字节	百万亿亿亿字节	Nona Byte		NB	2^100
十亿亿亿亿字节	十亿亿亿亿字节	Dogga Byte		DB	2^110
万亿亿亿亿字节	万亿亿亿亿字节	Corydon Byte	CB	2^120
1KB=1024B，一个汉字 =2B，即1KB=512个汉字占用的空间。
1TB=1024GB 1GB=1024MB 1MB=1024KB 1KB=1024B 1B=8b.
*/


    /**
     * 这里只把B转换成KB或者MB(xx.xx)
     * (1024换算,计算文件大小一般用1024)
     * @param sizes  long
     * @return String
     */
    public static String bToOther1024(long sizes){
        DecimalFormat df = new DecimalFormat("#.00");
        String s = "";//要返回的文件大小
        float size = sizes;
        if(size>=1024 && (size/1024<=1024)){//转换成KB
            s = size/1024+"KB";
        }
        if(size/1024>1024){//转换成MB
            float ss= size/1024/1024;
            s = df.format(ss) +"MB";

        }
        return s;

    }
    /**
     * 这里只把B转换成KB或者MB
     * (1000换算)
     * @param  sizes  long
     * @return String
     */
    public static String bToOther1000(long sizes){
        String s = "";
        if(sizes>=1000 && (sizes/1000<=1000)){//转换成KB
            s = sizes/1000+"KB";
        }
        if(sizes/1000>1000){//转换成MB
            s = sizes/1000 +"MB";
        }
        return s;
    }

}
